(function () {

	//获取备件合同细目数据 服务器分页
    var contractReplacementData = {};
    contractReplacementData.contractId=jQuery('#contractId').val();
    var serverReplacementTable;
    
    jQuery(document).ready(function () {
    	jQuery('#amount').blur(function() {
    		packOff();
    	});
    	jQuery('#price').blur(function() {
    		packOff();
    	});
    	jQuery('#type').change(function() {
    		$("#cusMaterielSpec").val($(this).val())
    	});
    	jQuery('#deviceName').change(function() {
    		$("#cusMaterielName").val($(this).val())
    	});
    	
    	
    	
    	jQuery(".move").click(function(){
    		var type=$(this).attr("data-toggle");
    		var selects=getSelect("#resultReplacementTable",1);
    		if(selects.length==1){
    			var changeNum;
    			if(type=="up"){
    				changeNum=-1;
    			}else{
    				changeNum=1;
    			}
    			var id=selects[0].id;
    			var indexOrder=selects[0].indexOrder;
    			var contractID=selects[0].contractID;
    			jQuery(".btn").attr("disabled",true);
    			var url=window.rootPath+"/ui/contract/changeReplaceIndex?id="+id+"&oldIndexOrder="+indexOrder
    			+"&changeNum="+changeNum+"&contractID="+contractID;
    			 jQuery.ajax({
    	               	type : 'get',
    	               	url : encodeURI(url),
    	               	dataType : 'json',
    	               	contentType : 'application/json;charset=utf-8',
    	               	success : function(data) {
    	               		serverReplacementTable.draw(false)
    	               		jQuery(".btn").attr("disabled",false);
    	               	}
    	               });
    			
    		}else if(selects.length>1){
    			message("单条移动")
    		}
    		
    	})
    	
    	
    	$('.clearPrice').click(function() {
    		var selects=getSelect("#resultReplacementTable",1);
    		
    		if(selects.length==0) return;
    		
    		
    		var ids=selects[0].id;
    		
    		for(var i=1;i<selects.length;i++){
    			ids+=","+selects[i].id;
    		}
    		var url=window.rootPath+'/ui/contract/clearPrice?ids='+ids;
    		  jQuery.ajax({
                 	type : 'get',
                 	url : encodeURI(url),
                 	dataType : 'json',
                 	contentType : 'application/json;charset=utf-8',
                 	success : function(data) {
                 		serverReplacementTable.draw(false)
                 	}
                 });    		
    		
    		
		})
		$('.insert-re').click(function() {
			var selects=getSelect("#resultReplacementTable",1);
			if(selects.length==1){
				showReplacementModal(selects[0].indexOrder);
			}else if(selects.length>1){
				message("选择一条数据，在此之前插入")
			}
		})
    	
    	$(".has-feedback").click(function(event){
            //得到点击事件的dom结构
            var click_node = getEventTrigger(event);
            //得到点击close图片的data-close
            //data-close的值是input框的id
            var clickName = click_node.getAttribute("data-close");
            //得到点击事件的属性（INPUT）
            var clickInput = click_node.nodeName; 
            //判断点击的是close图片，则清空相应id输入框的值，并隐藏该close图片
            if(clickName=='price'){
                $("#"+clickName).val("");
                $('#totalPrice').val("");
                $("#"+clickName).next().css("display","none");
            }
            //判断点击事件的元素是input框
            if(clickInput=="INPUT"){
                //获取INPUT的id
                var next_closeId = click_node.id;
                //绑定获取焦点和输入值-函数
                $("#"+next_closeId).bind("focus keyup",function(){
                    //判断当前输入框的值不为空时
                    if($("#"+next_closeId).val()!=''){
                        $(".form-control-feedback").css("display","none"); 
                        //当前输入框的下一个同袍节点样式显示
                        $("#"+next_closeId).next().css("display","inline-block");
                    }
                    
                })
            }
        })
        //得到点击事件的dom结构
        function getEventTrigger(event)
          { 
              //ie 火狐 event兼容
              //参考资料： http://www.cnblogs.com/quanhai/archive/2010/04/20/1716149.html
               event = event? event: window.event
            　　var x = event.srcElement ? event.srcElement:event.target;
               return x;
          }
    	
    	
    	
    	//计算含税总价
    	var packOff = function() {
    		var packPrice = jQuery("#amount").val();
    		var packRatio = jQuery("#price").val();
    		if (!isNaN(Number(packPrice)) && !isNaN(Number(packRatio))) {
    			jQuery("#totalPrice").val((packPrice * packRatio).toFixed(2));
    		}
    	}
    	serverReplacementTable = jQuery('#resultReplacementTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "iDisplayLength":9999,
            "page":false,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url":window.rootPath+ '/ui/contract/getReplacement',
                "data": function (d) {
                    return $.extend({}, d, contractReplacementData);
                }
            },
            columns: [
                {
                	data: 'indexOrder'
                },
                {
    	            data: null,
    	            defaultContent: "",
    	            render: function (data, type, full, meta) {
    	            	var id=data.id
    	            	var operate ='<input type="checkbox" class="checkchildReplacement">';
    	            	return operate;
    	            }   
                },
                {
                    data: 'supplierCode'
                },
                {
                    data: 'deviceName'
                },
                {
                    data: 'type'
                },
                {
                	data: 'material'
                },
                {
                	data: 'unit'
                },
                {
                    data: 'amount'
                },
                {
                    data: 'nOneDiscount'
                },
                {
                    data: 'price'
                },
                {
                	 data: 'materialCoding'
                },
                {
                	data: 'branchFactory'
                },
                {
                	data: 'cusMaterielName'
                },
                {
                	data: 'cusMaterielSpec'
                },
                {
                	 data: 'memo',
                	 render:function(data,type,full,meta){
 							return '<font title="'+data+'">'+stringCut(data,12)+'</font>'
 					}
                }
                ],
            "drawCallback": function (oSettings) {
//                var k = 0;
//                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;
//
//                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
//                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
//                    k++;
//                }
                var data=oSettings.json.data;
                var total=0;
                for(var i=0;i<data.length;i++){
                	total+=data[i].price;
                }
                var tds="<tr><td  colspan='2'>含税总金额(元)</td>"
							+"<td colspan='11' >"+total+"</td>" 
						+"</tr>";
                jQuery("#resultReplacementTable tbody").append(tds);
                
            }
        });
    	//删除备件合同细目
    	jQuery('.delReplacementBtn').on('click', function () {
    		   var selects=getSelect("#resultReplacementTable",1);
    		   var url=window.rootPath+"/ui/contract/deleteReplacement";
    		   var contractId = jQuery("#contractId").val(); 
    		   var totalSum = jQuery("#totalSum").val();
    		   $("#checkAllReplacement").prop("checked", false);
    		   delSelect(selects,url,serverReplacementTable);
    		   var urlxy = window.rootPath + '/ui/contract/checkMoney?contractId=' + contractId + '&totalSum=' + totalSum;
    		   jQuery.ajax({
               	type : 'get',
               	url : encodeURI(urlxy),
               	dataType : 'json',
               	contentType : 'application/json;charset=utf-8',
               	success : function(data) {
               		if(data==0){
               			alert("合同金额与细目的总金额相同！");
               		} else if(data==1){
               			alert("合同金额小于细目的总金额！");
               		} else if(data==2){
               			alert("合同金额大于细目的总金额！");
               		}
               	}
               });
    		});
    	
    	//备件合同细目新建弹窗显示
    	jQuery('.addReplacementBtn').on('click', function () {
    		var contractId = jQuery('#contractId').val();
        	if(contractId == ""){
            	if (confirm("当前合同还未保存，是否保存？")) {
            		saveContract('addReplacementBtn');
            	}
            }else{
            	showReplacementModal();
            }
    	});
    	
    	//备件合同细目编辑弹窗显示
    	jQuery('.editReplacementBtn').on('click', function () {
    		var selects=getSelect("#resultReplacementTable",1);
    		if(selects.length==0){
 		       $.springLemonDialog({
 		         content: '请选择需要编辑的记录',// 确认文本
 		         clickButton: function (sender, modal, index) {// 按钮事件处理
 		             $(this).closeDialog(modal);
 		         }
 		       }); 
 		    }else if(selects.length==1){
 		    	var replacementId=selects[0].id;
 		    	var replacementcreateTime=selects[0].createTime;
  			    var supplierCode=selects[0].supplierCode;
  			    var deviceName=selects[0].deviceName;
  			    var type=selects[0].type;
  			    var material=selects[0].material;
  			    var unit=selects[0].unit;
  			    var amount=selects[0].amount;
  			    var price = selects[0].price;
  			    var nOneDiscount=selects[0].nOneDiscount;
  			    var memo=selects[0].memo;
  			    var materialCoding=selects[0].materialCoding;
  			    jQuery('#replacementId').val(replacementId);
  			    jQuery("#replacementcreateTime").val(replacementcreateTime);
	  			jQuery('#oneSupplierCode').val(supplierCode);
	  			jQuery('#deviceName').val(deviceName);
	  			jQuery('#type').val(type);
	  			jQuery('#material').val(material);
	  			jQuery('#unit').val(unit);
	  			jQuery('#amount').val(amount);
	  			jQuery('#price').val(nOneDiscount);
	  			jQuery('#totalPrice').val(price);
	  			jQuery("#branchFactory").val(selects[0].branchFactory);
      			jQuery("#cusMaterielName").val(selects[0].cusMaterielName);
      			jQuery("#cusMaterielSpec").val(selects[0].cusMaterielSpec);
      			jQuery("#indexOrder").val(selects[0].indexOrder);
      			 $("#price").next().css("display","inline-block");
	  			jQuery("#memo1").val(memo);
	  			jQuery("#materialCoding").val(materialCoding);
	  			jQuery('#moreSupplierCode').val('');
	  			jQuery('#ids').val('');
	  			jQuery("#selectContractId").val('');
	  			document.getElementById("editOneReplacementAtrrForm").style.display='block';
	  			document.getElementById("editMoreReplacementAtrrForm").style.display='none';
  			    jQuery('#editReplacementModal').modal('show');
   		    }else{
   		    	message("只能同时编辑一条信息")
   		    }
    		
 		});
    	jQuery('.batchToHost').on('click', function () {
    		
    		var selects=getSelect("#resultReplacementTable",1);
    		if(selects.length>0){
    			 var ids=selects[0].id;
   			   for(var i=1;i<selects.length;i++){
   				   ids += ',' + selects[i].id;  
   			   }
   			   jQuery('#ids').val(ids);
   			   jQuery('#replacementId').val('');
   			   jQuery("#replacementcreateTime").val('');
  	  		   jQuery('#oneSupplierCode').val('');
  	  		   jQuery('#deviceName').val('');
  	  		   jQuery('#type').val('');
  	  		   jQuery('#unit').val('');
  	  		   jQuery('#material').val('');
  	  		   jQuery('#amount').val('');
  	  		   jQuery('#totalPrice').val('');
  	  		   jQuery('#price').val('');
  	  		   jQuery('#moreSupplierCode').val('');
  	  		   jQuery("#selectContractId").val('');
  	  		   jQuery("#memo1").val('');
  	  		   jQuery("#indexOrder").val('');
  	  		 jQuery("#branchFactory").val("");
     			jQuery("#cusMaterielName").val("");
     			jQuery("#cusMaterielSpec").val("");
  	  		 jQuery("#materialCoding").val('');
   			   document.getElementById("editMoreReplacementAtrrForm").style.display='block';
   			   document.getElementById("editOneReplacementAtrrForm").style.display='none';
   			   jQuery('#editReplacementModal').modal('show');
    		}
    	})
    	//新建/编辑备件保存
    	jQuery('.saveReplacementBtn').on('click', function () {
    		$("#checkAllReplacement").prop("checked", false);
    		//单个备件保存
    		if(jQuery("#editOneReplacementAtrrForm").css("display")=='block' && jQuery("#editMoreReplacementAtrrForm").css("display")=='none'){
    			if(jQuery("#editOneReplacementAtrrForm") && !jQuery("#editOneReplacementAtrrForm").Validform({tiptype:3, showAllError:true}).check(false)){
                    return;
                };
                jQuery(".saveReplacementBtn").attr("disabled", true);
    			var replacementId = jQuery('#replacementId').val();
    			var totalSum = jQuery("#totalSum").val();
    			var createTime = jQuery("#replacementcreateTime").val();
    			var contractID = jQuery("#contractId").val();
    			var contractType = "备件合同";
      			var deviceName = jQuery('#deviceName').val();
      			var type = jQuery('#type').val();
      			var material = jQuery('#material').val();
      			var unit = jQuery('#unit').val();
      			var amount = jQuery('#amount').val();
      			var price = jQuery('#totalPrice').val();
      			var nOneDiscount = jQuery('#price').val();
      			var selectContractId = jQuery("#selectContractId").val();
      			var oneSupplierCode = jQuery("#oneSupplierCode").val();
      			var memo = jQuery("#memo1").val();
      			var indexOrder = jQuery("#indexOrder").val();
      			//使用分厂
      			var  branchFactory=jQuery("#branchFactory").val();
      			//客户物料名称
      			var  cusMaterielName=jQuery("#cusMaterielName").val();
      			//客户物料规格
      			var  cusMaterielSpec=jQuery("#cusMaterielSpec").val();
      			
      			var materialCoding = jQuery("#materialCoding").val();
      			//暂时将选择关联的项目合同ID与合同号存在数据的supplierCode中，方便使用；
      			if (replacementId == '') {
	      			var data={
	      					"contractID":contractID,
	                        "contractType":contractType,
	                        "supplierCode":selectContractId+":"+oneSupplierCode,
	                        "deviceName": deviceName,
	                        "type": type,
	                        "material": material,
	                        "unit": unit,
	                        "amount": amount,
	                        "nOneDiscount": nOneDiscount,
	                        "materialCoding": materialCoding,
	                        "price": price,
	                        "memo": memo,
	                        "branchFactory": branchFactory,
	                        "cusMaterielName": cusMaterielName,
	                        "cusMaterielSpec": cusMaterielSpec,
	                        "indexOrder": indexOrder,
	                    };
      			} else{
	      			var data={
	                        "id":replacementId,
	                        "createTime" : createTime,
	                        "contractID":contractID,
	                        "contractType":contractType,
	                        "supplierCode":selectContractId+":"+oneSupplierCode,
	                        "deviceName": deviceName,
	                        "type": type,
	                        "material": material,
	                        "unit": unit,
	                        "amount": amount,
	                        "nOneDiscount": nOneDiscount,
	                        "materialCoding": materialCoding,
	                        "price": price,
	                        "memo": memo,
	                        "branchFactory": branchFactory,
	                        "cusMaterielName": cusMaterielName,
	                        "cusMaterielSpec": cusMaterielSpec,
	                        "indexOrder": indexOrder,
	                    };
      			}
                    var url=window.rootPath+'/ui/contract/editOneReplacement';
                    var urlxy = window.rootPath + '/ui/contract/checkMoney?contractId=' + contractID + '&totalSum=' + totalSum;
                    jQuery.ajax({
                        url:encodeURI(url),
                        type:'post',
                        data:JSON.stringify(data),
                        dataType:'json',
                        contentType:'application/json;charset=utf-8',
                        success: function () {
                            jQuery('#editReplacementModal').modal('hide');
                            contractReplacementData.contractId=jQuery('#contractId').val();
                            serverReplacementTable.draw(false);
                            jQuery(".saveReplacementBtn").attr("disabled", false);
                            jQuery.ajax({
                            	type : 'get',
                            	url : encodeURI(urlxy),
                            	dataType : 'json',
                            	contentType : 'application/json;charset=utf-8',
                            	success : function(data) {
                            		if(data==0){
                            			alert("合同金额与细目的总金额相同！");
                            		} else if(data==1){
                            			alert("合同金额小于细目的总金额！");
                            		} else if(data==2){
                            			alert("合同金额大于细目的总金额！");
                            		}
                            	}
                            });
                        }

                    });
    		}
    		//多个备件保存
    		else if(jQuery("#editOneReplacementAtrrForm").css("display")=='none' && jQuery("#editMoreReplacementAtrrForm").css("display")=='block'){
    			if(jQuery("#editMoreReplacementAtrrForm") && !jQuery("#editMoreReplacementAtrrForm").Validform({tiptype:3, showAllError:true}).check(false)){
                    return;
                };
                jQuery(".saveReplacementBtn").attr("disabled", true);
                var contractID = jQuery("#contractId").val();
                var totalSum = jQuery("#totalSum").val();
                var ids = jQuery('#ids').val();
                var selectContractId = jQuery("#selectContractId").val();
                var url=window.rootPath+"/ui/contract/editMoreReplacement"+"?replacementInfo="+ ids +":"+ selectContractId;
                var urlxy = window.rootPath + '/ui/contract/checkMoney?contractId=' + contractID + '&totalSum=' + totalSum;
                jQuery.ajax({
                    url:encodeURI(url),
                    cache:false,
                    type : "get",
                    dataType:"json",
                    success:function(data){
                    	jQuery('#editReplacementModal').modal('hide');
                    	contractReplacementData.contractId=jQuery('#contractId').val();
                    	serverReplacementTable.draw(false);
                    	jQuery(".saveReplacementBtn").attr("disabled", false);
                    	jQuery.ajax({
                        	type : 'get',
                        	url : encodeURI(urlxy),
                        	dataType : 'json',
                        	contentType : 'application/json;charset=utf-8',
                        	success : function(data) {
                        		if(data==0){
                        			alert("合同金额与细目的总金额相同！");
                        		} else if(data==1){
                        			alert("合同金额小于细目的总金额！");
                        		} else if(data==2){
                        			alert("合同金额大于细目的总金额！");
                        		}
                        	}
                        });
                    }
                });
    		}
    	});
    	
    	//EXCEL导入
        jQuery('.importReplacementList').on("click",function()
        {
        	var contractId = jQuery('#contractId').val();
        	var type = '4';
        	if(contractId == ""){
            	if (confirm("当前合同还未保存，是否保存？")) {
            		saveContract('importReplacementList');
            	}
            }else{
            	fileUpload(contractId, type);
            }
        });
        
        /**
    	 * 保存备件合同
    	 */
        var saveContract = function(state) {
        	var signedDate = jQuery('#signedDate').val();
        	var giveOutDate = jQuery('#giveOutDate').val();
        	var scheduleDate = jQuery('#scheduleDate').val();
     		var operatDate = jQuery('#operatDate').val();
     		if (signedDate==""||giveOutDate==""||operatDate==""){
     			message("请将页面上所有日期信息完善，保存后还可进行编辑。");
     			return ;
     		}
     		var isId=jQuery("#contractId").val();
     		var contractcreateTime=jQuery("#createTime").val();
      	    var createTime=new Date(contractcreateTime).getTime();
            var supplierCode = jQuery('#supplierCode').val();
        	var demanderCode = jQuery('#demanderCode').val();
        	var contractType = jQuery('#contractType').val();
     		var totalSum = jQuery('#totalSum').val();
     		var projectCode = jQuery('#projectCode').val();
     		var stop = jQuery('#stop').val();
     		var freightCharge = jQuery('#freightCharge').val();
     		var projectName = jQuery('#projectName').val();
         	var payType = jQuery('#payType').val();
         	var guaranteePeriod = jQuery('#guaranteePeriod').val();
         	var breakDuty = jQuery('#breakDuty').val();
         	var customerId = jQuery("#customerId").val();
     		var orderUnit = jQuery('#orderUnit').val();
         	var orderDelegate = jQuery('#orderDelegate').val();
     		var orderPhone = jQuery('#orderPhone').val();
     		var industryInfo = jQuery('#industryInfo').val();
     		var orderAddress = jQuery('#orderAddress').val();
     		var orderZip = jQuery('#orderZip').val();
     		var orderArea = jQuery('#orderArea').val();
     		var invoiceBank = jQuery("#invoiceBank").val();
      		var bankAccount = jQuery("#bankAccount").val();
      		var taxNumber = jQuery("#taxNumber").val();
      		var invoiceAddress = jQuery("#invoiceAddress").val();
     		var postUnit = jQuery('#postUnit').val();
         	var postDelegate = jQuery('#postDelegate').val();
     		var postPhone = jQuery('#postPhone').val();
     		var postAddress = jQuery('#postAddress').val();
     		var postZip = jQuery('#postZip').val();
     		var dutyArea = jQuery('#dutyArea').val();
     		var dutyOfficer = jQuery('#dutyOfficer').val();
     		var southNorthArea = jQuery('#southNorthArea').val();
     		var belongArea = jQuery('#belongArea').val();
     		var checkKind = jQuery('#checkKind').val();
     		var productKind = jQuery('#productKind').val();
     		var signOfficer = jQuery('#signOfficer').val();
     		var repairOfficer = jQuery('#repairOfficer').val();
     		var quotationOfficer = jQuery('#quotationOfficer').val();
     		var operatDepartment = jQuery('#operatDepartment').val();
     		var operator = jQuery('#operator').val();
     		var memo = jQuery('#memo').val();
     		var state = jQuery('#state').val();
     		var cstate = jQuery('#cstate').val();
      		if(isId == ""){// 新增合同
      			var d = {
         				"user":{"id":$("#userId").val()},
                    	"supplierCode": supplierCode,
                    	"demanderCode": demanderCode,
                    	"contractType": contractType,
                        "totalSum": totalSum,
                        "signedDate": signedDate,
                        "scheduleDate": scheduleDate,
                        "giveOutDate": giveOutDate,
                        "projectCode": projectCode,
                        "stop": stop,
                        "freightCharge": freightCharge,
                        "projectName": projectName,
                        "payType": payType,
                        "guaranteePeriod": guaranteePeriod,
                        "breakDuty": breakDuty,
                        "customerId": customerId,
                        "orderUnit": orderUnit,
                        "orderDelegate": orderDelegate,
                        "orderPhone": orderPhone,
                        "industryInfo": industryInfo,
                        "orderAddress": orderAddress,
                        "orderZip": orderZip,
                        "orderArea": orderArea,
                        "invoiceBank": invoiceBank,
      	                "bankAccount": bankAccount,
      	                "taxNumber": taxNumber,
      	                "invoiceAddress": invoiceAddress,
                        "postUnit": postUnit,
                        "postDelegate": postDelegate,
                        "postPhone": postPhone,
                        "postAddress": postAddress,
                        "postZip": postZip,
                        "dutyArea": dutyArea,
                        "dutyOfficer": dutyOfficer,
                        "southNorthArea": southNorthArea,
                        "belongArea": belongArea,
                        "checkKind": checkKind,
                        "productKind": productKind,
                        "signOfficer": signOfficer,
                        "repairOfficer": repairOfficer,
                        "quotationOfficer": quotationOfficer,
                        "operatDepartment": operatDepartment,
                        "operator": operator,
                        "operatDate": operatDate,
                        "memo": memo,
                        "state": state,
                        "cstate": cstate,
                };
      		}else{
      			var d = {
      					"id": isId,
  	        			"createTime": createTime,
                    	"supplierCode": supplierCode,
                    	"demanderCode": demanderCode,
                    	"contractType": contractType,
                        "totalSum": totalSum,
                        "signedDate": signedDate,
                        "scheduleDate": scheduleDate,
                        "giveOutDate": giveOutDate,
                        "projectCode": projectCode,
                        "stop": stop,
                        "freightCharge": freightCharge,
                        "projectName": projectName,
                        "payType": payType,
                        "guaranteePeriod": guaranteePeriod,
                        "breakDuty": breakDuty,
                        "customerId": customerId,
                        "orderUnit": orderUnit,
                        "orderDelegate": orderDelegate,
                        "orderPhone": orderPhone,
                        "industryInfo": industryInfo,
                        "orderAddress": orderAddress,
                        "orderZip": orderZip,
                        "orderArea": orderArea,
                        "invoiceBank": invoiceBank,
      	                "bankAccount": bankAccount,
      	                "taxNumber": taxNumber,
      	                "invoiceAddress": invoiceAddress,
                        "postUnit": postUnit,
                        "postDelegate": postDelegate,
                        "postPhone": postPhone,
                        "postAddress": postAddress,
                        "postZip": postZip,
                        "dutyArea": dutyArea,
                        "dutyOfficer": dutyOfficer,
                        "southNorthArea": southNorthArea,
                        "belongArea": belongArea,
                        "checkKind": checkKind,
                        "productKind": productKind,
                        "signOfficer": signOfficer,
                        "repairOfficer": repairOfficer,
                        "quotationOfficer": quotationOfficer,
                        "operatDepartment": operatDepartment,
                        "operator": operator,
                        "operatDate": operatDate,
                        "memo": memo,
                        "state": state,
                        "cstate": cstate,
                };
      		}
      		jQuery(".addReplacementBtn").attr("disabled", true);
      		jQuery(".importReplacementList").attr("disabled", true);
      		var id=isId;
      		if (id==null||id==''){
      			id = 'null';
      		}
      		if (cstate=="已完成"){
      			$.springLemonDialog({
  					content : '该合同已经生产商品计划，不能保存！',// 确认文本
  					clickButton : function(sender, modal, index) {// 按钮事件处理
  						$(this).closeDialog(modal);
  					}
      			});
  			}
      		if(cstate=="已排产"){
      			alert("保存合同后将修改排产相关信息。");
      		}
      		if (supplierCode!=''){// 验证供方合同号是否已存在
      			var urlValid=window.rootPath+"/ui/contract/validSupplierCode/"+id+"/"+supplierCode;
      	    	jQuery.ajax({
      	            url:encodeURI(urlValid),
      	            cache:false,
      	            type :"get",
      	            dataType:"json",
      	            contentType:"application/json;charset=utf-8",// 解决返回数据中的中文乱码问题
      	            success:function(data){
      	            	if(data.codeState==1){
      	            		$.springLemonDialog({
     		      		         content: '供方合同号已存在，请修改！',// 确认文本
     		      		         clickButton: function (sender, modal, index) {// 按钮事件处理
     		      		             $(this).closeDialog(modal);
     		      		         }
     		            		});
      	            		jQuery(".addReplacementBtn").attr("disabled", false);
      	            		jQuery(".importReplacementList").attr("disabled", false);
      	            		return;
      	            	}
      	                    var url = window.rootPath + "/ui/contract/saveContractPart";
      	                    jQuery.ajax({
      	                        type: 'post',
      	                        url: url,
      	                        data: JSON.stringify(d),
      	                        dataType: 'json',
      	                        contentType: 'application/json;charset=utf-8',
      	                        success: function (data) {
      	                        	var contractId = data.contractId;
      	                        	var time=moment(data.createTime).format("YYYY-MM-DD HH:mm:ss")
      	                        	jQuery("#createTime").val(time);
      	                        	jQuery("#contractId").val(contractId);
      	                        	jQuery(".addReplacementBtn").attr("disabled", false);
      	                    		jQuery(".importReplacementList").attr("disabled", false);
      	                        	if (state=="addReplacementBtn"){
      	                        		showReplacementModal();
      	                        	}else if(state=="importReplacementList"){
      	                        		var type = '4';
      	                        		fileUpload(contractId, type);
      	                        	}
      	                        }
      	                    });
      	            }
      	    	});
      		}else{
      	            var url = window.rootPath + "/ui/contract/saveContractPart";
      	            jQuery.ajax({
      	                type: 'post',
      	                url: url,
      	                data: JSON.stringify(d),
      	                dataType: 'json',
      	                contentType: 'application/json;charset=utf-8',
      	                success: function (data) {
      	                	var contractId = data.contractId;
      	                	var time=moment(data.createTime).format("YYYY-MM-DD HH:mm:ss")
	                        jQuery("#createTime").val(time);
      	                	jQuery("#contractId").val(contractId);
      	                	jQuery(".addReplacementBtn").attr("disabled", false);
      	            		jQuery(".importReplacementList").attr("disabled", false);
	                        if (state=="addReplacementBtn"){
	                        	showReplacementModal();
	                       	}else if(state=="importReplacementList"){
  	                        	var type = '4';
  	                       		fileUpload(contractId, type);
  	                       	}
      	                }
      	            });
      		}
      	};
        
        /**
      	 * 添加备件时初始化弹窗
      	 */
        var showReplacementModal = function(order) {
        	
        	
        	if(order){
        		jQuery('#indexOrder').val(order);
        	}else{
        		jQuery('#indexOrder').val('');
        	}
        	jQuery('#replacementId').val('');
        	jQuery("#replacementcreateTime").val('');
  			jQuery('#oneSupplierCode').val('');
  			jQuery('#deviceName').val('');
  			jQuery('#type').val('');
  			jQuery('#material').val('');
  			jQuery('#unit').val('');
  			jQuery('#amount').val('');
  			jQuery('#price').val('');
  			jQuery('#totalPrice').val('');
  			jQuery('#memo1').val('');
  			 jQuery("#branchFactory").val("");
 			jQuery("#cusMaterielName").val("");
 			jQuery("#cusMaterielSpec").val("");
  			jQuery('#moreSupplierCode').val('');
  			jQuery("#materialCoding").val('');
  			jQuery('#ids').val('');
  			 $("#price").next().css("display","none");
  			jQuery("#selectContractId").val('');
  			document.getElementById("editOneReplacementAtrrForm").style.display='block';
  			document.getElementById("editMoreReplacementAtrrForm").style.display='none';
			jQuery('#editReplacementModal').modal('show');
        }
    	
    	/**
    	 * 文件上传插件
    	 */
    	var fileUpload = function(contractId, type) {
    		var root = window.rootPath;
    		WebFilesUploader(
    				{
    					_webuploader : {
    						server : root + '/ui/contract/import/' + contractId +'/'+ type,
    						swf : root
    								+ '/resources/poweradminjs/webupload/webfilesuploader/Uploader.swf',
    						chunked:false		
    					}
    				
    				}, function(jsons) {  		
    					contractReplacementData.contractId=jQuery('#contractId').val();
    					serverReplacementTable.draw(true);
    				});
           
    	
    	};
    	
    	//列表中的全选
        $("#checkAllReplacement").click(function(){
        	var check = $(this).prop("checked");
            $(".checkchildReplacement").prop("checked", check);
    	});
    	
    });
})();